package com.oz.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oz.Utils;
//import com.oz.Utils;
import com.oz.entity.DemoEntity;
import com.oz.mapper.DemoMapper;
//import com.oz.mapper.UserMapper;

@RestController
@RequestMapping("/demo")
public class DemoAction {

	java.util.logging.Logger log = java.util.logging.Logger.getLogger(this.getClass().getName());

	@Autowired
	DemoMapper demoMapper;

//	@Autowired
//	UserMapper userMapper;

	// 新增 or 增改
	@RequestMapping(value = "/createorupdate")
	public Object messageCreateOrUpdate(@ModelAttribute DemoEntity message) {
		log.info("message.getId()-------------------> " + "".equals(message.getId()));
		log.info("-------------------> " + JSON.toJSONString(message, JSONWriter.Feature.PrettyFormat,
				JSONWriter.Feature.WriteNullStringAsEmpty));
		if (StringUtils.hasText(message.getId())) {
			// 确定了文章标题 name，才能以name为文件夹，保存文章为文本文件, 对应图片等 也保存在其中
			String temp = message.getResource();
			if (StringUtils.hasText(temp)) {
//				if ((temp.length() > 100 || !new File(Utils.UPLOADPATH + temp).isFile())) {
//					temp = Utils.contentSaveToFile(temp,"项目", message.getName(), message.getId());
//					message.setResource(temp);
//				}
			}
			log.info("----------这里加入了修改20190802---------> " + JSONObject.toJSONString(message,
					JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteNullStringAsEmpty));

			demoMapper.updateById(message);
		} else {
			message.setId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
			demoMapper.insert(message);
		}
//		return "{\"code\":20000,\"rId\":\"" + message.getId() + "\"}";
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 20000);
		jsonObject.put("rId", message.getId());
		return jsonObject;
	}

	// 删
	@RequestMapping(value = "/del")
	public Object messageDelete(String id) {
		Integer deletedCount = demoMapper.deleteById(id);
//		return "{\"code\":20000,\"deletedCount\":" + deletedCount + "}";
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 20000);
		jsonObject.put("deletedCount", deletedCount);
		return jsonObject;
	}

	// 查
	@RequestMapping(value = "/list")
	public Object messagelist(@ModelAttribute DemoEntity message, String orderBy, String start, String end,
			@RequestParam(required = true, defaultValue = "1") Integer p,
			@RequestParam(required = true, defaultValue = "10") Integer pageSize) {
//		log.info("-------start------------> " + start);
//		log.info("-------end--------> " + end);
//		log.info("-------orderBy--------> " + orderBy);
//		log.info("-------------------> " + JSONObject.toJSONString(message));

//		log.info("---------query----------> " + JSONObject.toJSONString(ro.getList()));
//		log.info("-------------------> " + JSONObject.toJSONString(ro.getList(),SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue));
//		return "{\"code\":20000,\"total\":" + ro.getTotal() + ",\"pageNum\":" + ro.getPageNum() + ",\"list\":" + JSONObject.toJSONString(ro.getList(),SerializerFeature.WriteMapNullValue) + "}";
		QueryWrapper<DemoEntity> query = new QueryWrapper<DemoEntity>();
		if (StringUtils.hasText(start)) {
			query.gt("date1", start);
		}
		if (StringUtils.hasText(end)) {
			query.lt("date1", end);
		}
		if (StringUtils.hasText(message.getId())) {
			query.eq("id", message.getId());
		}
		if (StringUtils.hasText(message.getName())) {
			query.like("name", message.getName());
		}
		if (StringUtils.hasText(message.getRegion())) {
			query.like("region", message.getRegion());
		}

		if (StringUtils.hasText(orderBy)) {
			for (String element : orderBy.split(",")) {
				String[] sort = element.split(" ");
				if ("ASC".equals(sort[1]))
					query.orderByAsc(sort[0]);
				else
					query.orderByDesc(sort[0]);
			}
		}

		Page<DemoEntity> rq = demoMapper.selectPage(new Page<>(p, pageSize), query);
//		log.info("----------这里加入了修改20190802---------> "
//				+ JSONObject.toJSONString(rq.getRecords(), JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteNullStringAsEmpty));
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 20000);
		jsonObject.put("total", rq.getTotal());
		jsonObject.put("pageNum", rq.getCurrent());
		jsonObject.put("list", rq.getRecords());
		return jsonObject;
	}

	// 单个文件上传,带title,id 则为路径
	@RequestMapping(value = "/upload")
	public Object update(@RequestParam("upfs") MultipartFile[] files, String id, String title) {
		String basicPath = StringUtils.hasText(title) ? title + (StringUtils.hasText(id) ? '/' + id : "/") : (StringUtils.hasText(id) ? id + '/' : "");
		File path = new File(StringUtils.cleanPath(Utils.UPLOADPATH + '/' + basicPath));
		if(!path.exists())
			path.mkdirs();
		log.info("..........上传文件时， 文件个数......" + files.length + "...大小...." + files[0].getSize());
		try {
			JSONArray jsonArr = new JSONArray();
			for (int i = 0; i < files.length; i++) {
				String name = i + "_" + files[i].getOriginalFilename().replaceAll("[^\\u4E00-\\u9FA5A-Za-z0-9\\.]", "_");
				name = name.replaceAll("([^\\.]{0,6}).*(\\..{3,6})", "$1_" + new SimpleDateFormat("yyMMddhhmmss").format(Calendar.getInstance().getTime()) + "$2");
				FileCopyUtils.copy(files[i].getBytes(), new File(StringUtils.cleanPath(Utils.UPLOADPATH + '/' + basicPath + '/' + name)));
				jsonArr.add(JSON.parse("{'name':\"" + name + "\",'url':\""	+ (basicPath + '/' + name).replaceAll("(/+)|(\\+)", "/") + "\"}"));
			}
			return JSON.parse("{code:200000,data:"+ (jsonArr.size()==1?jsonArr.get(0):jsonArr) +"}");
		} catch (IOException e) {
			e.printStackTrace();
			return JSON.parse("{code:500000,rId:\"\"}");
		}

	}

}
